package com.atguigu.gmall.user.controller;


import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.AuthContext;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("api/user")
@RestController
public class UserCortroller {

    @Autowired
    UserService userService;

    @GetMapping("/address/list")
    public List<UserAddress> getCurrentUserAddress(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.getUserAddressListByUserId(userId);
    }



    @GetMapping("/passport/logout")
    public Result logout(@RequestHeader(value = "token",required = false) String headerToken,
                         @CookieValue(value = "token",required = false) String cookieToken){
        String token = headerToken;
        if (StringUtils.isEmpty(token)){
            token = cookieToken;
        }
        userService.logout(token);

        return Result.ok();
    }


    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo info,
                        HttpServletRequest request){

        UserInfo userInfo = userService.login(info);


        if (userInfo == null){

            return Result.build(null, ResultCodeEnum.PASSWDERROR);
        }
        //登录成功
        Map<String,Object> success = userService.hanleLoginSuccess(userInfo,request);
        return Result.ok(success);
    }


}
